module bookmark_ui


define listbookmark(bm: Bookmark, bmentry : BookmarkEntry)
{
  table {
    
    row {
      column[class:=date]{
        output(bm.date)
      }
      column[class:=url] {
        navigate(url(bm.url)){output(bm.url)}
      }
      column[class:=ref] {
        navigate(bookmark_references(bm)){output(bm.popularity)}
      }
    }
    if(bmentry != null) {
      // bookmark entry properties
      row {
        column[class:=date] {
          output(bmentry.date)
          " : "
          navigate(homepage(bmentry.user, false, "")){output(bmentry.user.name)}
        }
        column[class:=title] {
          output(bmentry.title)
        }
        column[class:=ctrl] {
          navigate(bookmarkentry_edit(bmentry)){"EDIT"}
          " | "
          actionLink("DELETE", delete())
        }
      }
      // bookmark entry list of tags
      row {
        column[class:=tags] {
          for(tgentry: TagEntry in bmentry.tgentries) {
              navigate(tag_references(tgentry.tag)){output(tgentry.tag.name)}
              " "
          }
        }
        column {}
        column {}
      }
    }
  }
  action delete() {
    bmentry.user.bmentries_remove(bmentry);
  }
}

// System bookmarks
define page bookmarks(popsort: Bool, filt: String)
{main(bookmarkswiki){
  var bmlist: List<Bookmark>
  init 
  {
    if(popsort) {
      bmlist := from Bookmark as bm order by bm.popularity desc;
    } else {
      bmlist := from Bookmark as bm order by bm.date desc;
    }
  }

  par {
    form {
      if(popsort) {
        "most popular bookmarks"
        actionLink(" (view most recent)", action{return bookmarks(false, filt);})
      } else {
        "most recent bookmarks"
        actionLink(" (view most popular)", action{return bookmarks(true, filt);})
      }
      " "
      input(filt)
      actionLink("filter", action{return bookmarks(popsort, filt);})
    }
  }

  // Display list according to parameters
  list {
    for(bm: Bookmark in bmlist where bm.matches(filt)) {
      listitem {
        bookmarks_listbookmark(bm) 
      }
    }
  }
 
}}

// Display bookmark() or bookmarkentry()
define template bookmarks_listbookmark(bm : Bookmark)
{
  var princbmentry : BookmarkEntry := null
  init {
    if(securityContext.loggedIn) {
      princbmentry := bm.bmentries_fromuser(securityContext.principal); 
    }
  }
  listbookmark(bm, princbmentry)
}

// Display all bookmark entries related to a given bookmark
define page bookmark_references(bm: Bookmark)
{main(bookmark_referenceswiki){
  var princbmentry: BookmarkEntry := null
  init {
    if(securityContext.loggedIn) {
      princbmentry := bm.bmentries_fromuser(securityContext.principal);
    }
  }
  
  listbookmark(bm, princbmentry)
  spacer
  list {
    for(bmentry: BookmarkEntry in bm.bmentries where bmentry != princbmentry) {
      listitem {
        listbookmark(bm, bmentry)
      }
    }
  }
  
}}